#include "Huiduo.h"

// 添加超时宏定义
#define I2C_TIMEOUT 10000  // 根据实际时钟调整超时值

void IRI2C_WriteByte(uint8_t addr, uint8_t dat) {
    uint8_t temp[2] = {addr, dat};
    uint32_t timeout = I2C_TIMEOUT;


    DL_I2C_fillControllerTXFIFO(I2C_0_INST, temp, 2);
    
    // 带超时的空闲状态检查
    while (!(DL_I2C_getControllerStatus(I2C_0_INST) & DL_I2C_CONTROLLER_STATUS_IDLE) && timeout--) {
        __NOP();  // 插入空指令防止编译器优化
    }
    if (!timeout) return;  // 超时处理

    DL_I2C_startControllerTransfer(I2C_0_INST, IR_I2C_ADDR, DL_I2C_CONTROLLER_DIRECTION_TX, 2);
    
    // 带超时的忙状态检查
    timeout = I2C_TIMEOUT;
    while ((DL_I2C_getControllerStatus(I2C_0_INST) & DL_I2C_CONTROLLER_STATUS_BUSY_BUS) && timeout--) {
        __NOP();
    }
    DL_I2C_flushControllerTXFIFO(I2C_0_INST);
}

uint8_t IRI2C_ReadByte(uint8_t addr) {
    uint8_t data = 0;
    uint32_t timeout = I2C_TIMEOUT;


    DL_I2C_fillControllerTXFIFO(I2C_0_INST, &addr, 1);

    // 带超时的空闲状态检查
    while (!(DL_I2C_getControllerStatus(I2C_0_INST) & DL_I2C_CONTROLLER_STATUS_IDLE) && timeout--) {
        __NOP();
    }
    if (!timeout) return 0;  // 超时返回默认值

    DL_I2C_startControllerTransfer(I2C_0_INST, IR_I2C_ADDR, DL_I2C_CONTROLLER_DIRECTION_TX, 1);
    
    timeout = I2C_TIMEOUT;
    while ((DL_I2C_getControllerStatus(I2C_0_INST) & DL_I2C_CONTROLLER_STATUS_BUSY_BUS) && timeout--) {
        __NOP();
    }
    if (!timeout) return 0;

    // 接收数据
    DL_I2C_startControllerTransfer(I2C_0_INST, IR_I2C_ADDR, DL_I2C_CONTROLLER_DIRECTION_RX, 1);
    
    timeout = I2C_TIMEOUT;
    while ((DL_I2C_getControllerStatus(I2C_0_INST) & DL_I2C_CONTROLLER_STATUS_BUSY_BUS) && timeout--) {
        __NOP();
    }
    if (!timeout) return 0;

    data = DL_I2C_receiveControllerData(I2C_0_INST);
    return data;
}

struct huiduo Huiduo ;

void deal_IRdata()
{
	u8 IRbuf = 0xFF;
	IRbuf = IRI2C_ReadByte(0x30);
	
	Huiduo.x1 = (IRbuf>>7)&0x01;
	Huiduo.x2 = (IRbuf>>6)&0x01;
	Huiduo.x3 = (IRbuf>>5)&0x01;
	Huiduo.x4 = (IRbuf>>4)&0x01;
	Huiduo.x5 = (IRbuf>>3)&0x01;
	Huiduo.x6 = (IRbuf>>2)&0x01;
	Huiduo.x7 = (IRbuf>>1)&0x01;
	Huiduo.x8 = (IRbuf>>0)&0x01;
}


void Huidu_Init(void)
{
    NVIC_ClearPendingIRQ(Huidu_Time_INST_INT_IRQN);
	NVIC_EnableIRQ(Huidu_Time_INST_INT_IRQN);
}



struct transition_counter counter = {-1};  // 全局计数器

// 检测状态转换（带消抖延时）
void Check_WB_BW(void) 
{
    static uint8_t last_stable_state = 0xFF;  // 初始稳定状态：全白
    static uint8_t debounce_state = 0;        // 消抖状态机：0=稳定, 1=WB检测中, 2=BW检测中
    static uint8_t debounce_counter = 0;      // 消抖计数器（10ms为单位）
    static uint8_t initialized = 0;           // 初始化标志
    static uint16_t disable_counter = 0;      // 新增：禁用检测计数器（1.5s = 150*10ms）
    
    // 新增：如果处于禁用期，只更新计数器并跳过所有检测逻辑
    if (disable_counter > 0) {
        disable_counter--;
        return;  // 完全跳过状态检测
    }
    
    // 读取当前状态（1=白, 0=黑）
    uint8_t current_state = (Huiduo.x1 & 1) << 0 |
                           (Huiduo.x2 & 1) << 1 |
                           (Huiduo.x3 & 1) << 2 |
                           (Huiduo.x4 & 1) << 3 |
                           (Huiduo.x5 & 1) << 4 |
                           (Huiduo.x6 & 1) << 5 |
                           (Huiduo.x7 & 1) << 6 |
                           (Huiduo.x8 & 1) << 7;
    
    // 首次运行初始化
    if (!initialized) {
        last_stable_state = current_state;  // 用实际状态初始化
        initialized = 1;                    // 标记已初始化
        return;                             // 跳过首次检测
    }
    
    // 状态机处理
    switch (debounce_state) {
        case 0:  // 稳定状态
            // 检测WB转换：全白 → 非全白
            if (last_stable_state == 0xFF && current_state != 0xFF) {
                debounce_state = 1;        // 进入WB消抖检测
                debounce_counter = 2;      // 设置消抖时间20ms (2*10ms)
            }
            // 检测BW转换：非全白 → 全白
            else if (last_stable_state != 0xFF && current_state == 0xFF) {
                debounce_state = 2;        // 进入BW消抖检测
                debounce_counter = 2;      // 设置消抖时间20ms (2*10ms)
            }
            break;
        
        case 1:  // WB转换消抖中
            if (debounce_counter > 0) {
                debounce_counter--;        // 递减计数器
            }
            
            // 消抖结束且状态稳定为非全白
            if (debounce_counter == 0) {
                if (current_state != 0xFF) {
                    counter.count++;       // 增加计数器
                    last_stable_state = current_state;   // 更新稳定状态
                    disable_counter = 150; // 新增：禁用检测1.5s (150*10ms)
                }
                debounce_state = 0;        // 返回稳定状态
            }
            // 消抖期间状态回退到全白，取消转换
            else if (current_state == 0xFF) {
                debounce_state = 0;        // 取消转换
            }
            break;
        
        case 2:  // BW转换消抖中
            if (debounce_counter > 0) {
                debounce_counter--;        // 递减计数器
            }
            
            // 消抖结束且状态稳定为全白
            if (debounce_counter == 0) {
                if (current_state == 0xFF) {
                    counter.count++;       // 增加计数器
                    last_stable_state = current_state;   // 更新稳定状态
                    disable_counter = 150; // 新增：禁用检测1.5s (150*10ms)
                }
                debounce_state = 0;        // 返回稳定状态
            }
            // 消抖期间状态回退到非全白，取消转换
            else if (current_state != 0xFF) {
                debounce_state = 0;        // 取消转换
            }
            break;
    }
}

// 定时器中断处理函数（每10ms调用一次）
void Huidu_Time_INST_IRQHandler(void) 
{
    if( DL_TimerG_getPendingInterrupt(Huidu_Time_INST) == DL_TIMER_IIDX_ZERO )
    {
        deal_IRdata();        // 读取红外数据
        Check_WB_BW();        // 检测黑白转换（带消抖）
    }
}

